<template>
  <main class="center">
    <div class="table-head">
      <div class="table-row flex gap-2">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="tabClick">
          <el-tab-pane label="考勤表" name="first">
            <div class="upload-btn">
              <el-upload ref="mainupload" v-model:file-list="mainFile"
                action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" multiple
                :before-upload="checkFileType"
                :on-change="(file, uploadFiles) => handleChange(file, uploadFiles, 'first')" :on-preview="handlePreview"
                :on-remove="handleRemove" :limit="1" :on-exceed="replay" :auto-upload="false" :show-file-list="false"
                :accept="accept">
                <el-button v-if="mainFile.length < 1" type="primary">导入</el-button>
                <el-button v-else type="primary">重新上传</el-button>
                <el-button v-if="mainFile.length > 0 && fileList.length > 0" type="primary"
                  @click.stop="handleFormat">合并</el-button>
                <el-button type="success" @click.stop="handleExprot">导出</el-button>
              </el-upload>
            </div>
          </el-tab-pane>
          <el-tab-pane label="附表" name="second">
            <div class="upload-btn">
              <el-upload v-model:file-list="fileList"
                action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" multiple
                :before-upload="checkFileType" :on-change="handleChange" :on-preview="handlePreview"
                :on-remove="handleRemove" :limit="3" :on-exceed="handleExceed" :auto-upload="false"
                :show-file-list="false" :accept="accept">
                <el-button v-if="fileList.length < 3" type="primary">导入</el-button>

                <el-button v-if="mainFile.length > 0 && fileList.length > 0" type="primary"
                  @click.stop="handleFormat">合并</el-button>
                <el-button type="success" @click.stop="handleExprot">导出</el-button>
              </el-upload>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="tags" v-if="fileList.length > 0 && activeName=='second'">
        <div class="flex gap-2">
          <el-tag v-for="(f, idx) in fileList" @click="handlePreview(f)" @close="removeClick(idx)" :key="idx"
            :name="filename(f.name)" :type="checktype(f.name)" closable>
            {{ filename(f.name) }}
          </el-tag>
        </div>
      </div>
    </div>

    <div id="luckysheet"></div>
  </main>
</template>

<script setup>
  import {
    ElMessage,
    ElMessageBox
  } from 'element-plus'
  import {
    exportExcel,
    handleData
  } from '../utils/exportExcel.js'
  import {
    genFileId
  } from 'element-plus'
  import LuckyExcel from 'luckyexcel'

  onMounted(() => {
    // 初始化表格activeName
    var options = {
      container: 'luckysheet', //luckysheet为容器id
      title: 'Demo', // 设定表格名称
      lang: 'zh'
    }
    luckysheet.create(options)
  })

  const fileList = ref([])

  const mainupload = ref(null)
  const mainFile = ref([])

  const exportJsondata = [];
  const exportMainJsondata = ref('')
  const luckysheetfiledata = ref([])
  const activeName = ref('first')
  const activeFileName = ref('')
  const accept = ref('.xlsx,.xls,.csv')

  const filename = (filename) => {
    let name = filename.substring(0, filename.lastIndexOf('.'))
    if (name.length <= 8) {
      return name
    }
    return name.slice(0, 5) + '...' + name.slice(-3)
  }
  const checktype = (name) => {
    return filename(name) == activeFileName.value ? 'primary' : 'info'
  }
  const replay = (files) => {
    mainupload.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    mainupload.value.handleStart(file)
  }

  const checkFileType = (file) => {
    console.log('checkFileType')

    const fileName = file.name
    const fileType = fileName.substring(fileName.lastIndexOf('.'))
    if (fileType !== '.xlsx' && fileType !== '.xls' && fileType !== '.csv') {
      setTimeout(() => {
        let index = fileList.value.findIndex((item) => fileName == item.name)
        fileList.value.splice(index, 1) // 删除指定索引的文件
      }, 500)
      ElMessage.error('请上传.xlsx、.xls或csv的文件！')
      return false
    }
    return true
  }
  const handleFormat = () => {
    console.log('handleFormat')
    if (fileList.value.length < 1) {
      ElMessage.error('请上传完整表格')
    }
    handleData(exportJsondata, exportMainJsondata.value).then(exportJson => {
      console.log(11111, exportJson)

      if (exportJson.err.length) {
        ElMessage.warning(`某表异常`)
      }



      luckysheet.create({
        container: 'luckysheet', // luckysheet is the container id
        data: exportJson.mainFile.sheets,
        title: '合并后',//exportMainJsondata.value.info.name,
        userInfo: exportMainJsondata.value.info.name.creator
      })
      console.log('adf',luckysheet.getAllSheets())
    });
  }
  const tabClick = (tab) => {
    console.log(tab.index, tab.paneName)
    console.log(mainFile.value[0])

    activeName.value = tab.paneName

    if (tab.index == 0 && mainFile.value[0]) {
      console.log(2222, mainFile.value[0])
      handlePreview(mainFile.value[0])
      return
    }
    if (tab.index == 1 && fileList.value.length > 0) {
      handlePreview(fileList.value[fileList.value.length - 1])
      return
    }

    luckysheet.create({
      container: 'luckysheet' // luckysheet is the container id
    })
  }

  const handleRemove = (file, uploadFiles) => {
    console.log(file, uploadFiles)
  }
  const removeClick = (index) => {
    let delname = filename(fileList.value[index].name)

    fileList.value.splice(index, 1)

    let filelen = fileList.value.length

    if (filelen == 0) {
      luckysheet.create({
        container: 'luckysheet' // luckysheet is the container id
      })
      return
    }
    console.log(delname)
    console.log(activeFileName.value)
    if (delname == activeFileName.value) {
      console.log(fileList.value[filelen])
      handlePreview(fileList.value[filelen - 1])
    }
  }

  const handlePreview = (uploadFile) => {
    console.log('uploadFile', uploadFile)
    LuckyExcel.transformExcelToLucky(uploadFile.raw, (exportJson, luckysheetfile) => {
      activeFileName.value = filename(exportJson.info.name)
      luckysheet.create({
        container: 'luckysheet', // luckysheet is the container id
        data: exportJson.sheets,
        title: exportJson.info.name,
        userInfo: exportJson.info.name.creator
      })
    })

  }

  const handleExceed = (type) => {
    console.log(type)
    ElMessage.warning(`最多上传4个文件，请重新选择`)
  }

  //TODO  选中多个文件的时候到最后一个文件再处理渲染逻辑
  const handleChange = (uploadFile, uploadFiles, name) => {
    console.log('uploadFiles', uploadFiles.length)
    if (!checkFileType(uploadFile)) {
      return
    }
    console.log('name', name)
    LuckyExcel.transformExcelToLucky(uploadFile.raw, (exportJson, luckysheetfile) => {
      luckysheetfiledata.value.push(luckysheetfile)
      activeFileName.value = filename(exportJson.info.name)
      if (name == 'first') {
        exportMainJsondata.value = exportJson
      } else {
        exportJsondata.push(exportJson)
      }
      luckysheet.create({
        container: 'luckysheet', // luckysheet is the container id
        data: exportJson.sheets,
        title: exportJson.info.name,
        userInfo: exportJson.info.name.creator
      })
    })

  }

  const handleExprot = () => {
    let luckysheetfile = luckysheet.getluckysheetfile()
    exportExcel('1123', luckysheetfile)


  }
</script>

<style lang="less" scoped>
  .tags {
    position: fixed;
    top: 20px;
    left: 140px;
  }

  .save-btn {
    position: fixed;
    z-index: 99;
    right: 50px;
    margin: 19px;
  }

  /deep/.el-tabs__content {
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
  }

  .table-head {
    position: fixed;
    left: 0;
    top: 0;
    padding: 10px;
  }

  .gap-2 {
    grid-gap: 0.5rem;
    gap: 0.5rem;
  }

  .flex {
    display: flex;
  }

  .tab {
    position: fixed;
    z-index: 99;
    left: 120px;
    top: 11px;
  }

  .upload-btn {
    position: fixed;
    z-index: 99;
    right: 150px;
    top: 0;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  #luckysheet {
    // display: none;
    margin: 0px;
    padding: 0px;
    position: absolute;
    width: 100%;
    height: 95%;
    left: 0px;
    top: 50px;
  }

  /deep/.luckysheet_info_detail_save,
  /deep/.luckysheet_info_detail_update {
    display: none;
  }
</style>
